<?php

namespace app\api\controller;

use app\common\controller\Wxpay;
use app\common\controller\Wxpay2;
use app\common\model\Help;
use app\common\model\Wechat;
use think\Request;
use library\Controller;
use think\Db;
use think\App;

class Mine extends Controller
{
    //小程序登录
    public $header;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $help = new Help();
        $this->header = $help->em_getallheaders();
    }

    public function index()
    {
        echo 'index';
    }

    // 获取微信小程序用户openid和session_key
    public function getOpenid(Wechat $wechat, Request $request, Help $help)
    {
        $wx_config = $wechat->mini_config($this->header);
        $param = $request->param();
        $code = $param['code'];                            //小程序传来的code值
        $appid = $wx_config['app_id'];                        //小程序的appid
        $appSecret = $wx_config['app_secret'];                //小程序的$appSecret
        $wxUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appSecret&js_code=$code&grant_type=authorization_code";
        $result = $help->curl_request($wxUrl);//请求拼接好的url
        $str = json_encode(array('msg' => '失败', 'code' => 400));
        if ($result) {
            $arr = json_decode($result, true);
            if (!empty($arr)) {
                if (!empty($arr['openid'])) {
                    $openid = $arr['openid'];
                    $rt = Db::table('store_member')->where('openid', $openid)->find();
                    if (empty($rt)) {
                        Db::table('store_member')->insert(['openid' => $openid, 'create_at' => date('Y-m-d H:i:s')]);
                    }
                    $rt = Db::table('store_member')->where('openid', $openid)->find();
                    $str = json_encode(array('msg' => '成功', 'code' => 200, 'data' => $rt));
                }
            }
        }
        echo $str;
    }


    // 设置用户信息
    public function set_info(Request $request)
    {
        //获取用户微信信息，包括昵称，头像等等
        $param = $request->param();

        $openid = $param['openid'];
        $gender = isset($param['gender']) ? $param['gender'] : 0;
        $avatar = isset($param['avatarUrl']) ? $param['avatarUrl'] : '';
        $nickname = isset($param['nickName']) ? $param['nickName'] : '';
        $phone = isset($param['phone']) ? $param['phone'] : '';

        if (strlen($openid) != 28) {
            //用户再次登录
            $data = ['code' => 400, 'data' => [], 'msg' => '请求失败'];
            echo json_encode($data);
            exit;
        }

        if (!empty($phone)) {
            Db::table('store_member')->where('openid', $openid)->update(['phone' => $phone]);
        }
        if (!empty($gender)) {
            Db::table('store_member')->where('openid', $openid)->update(['sex' => $gender]);
        }
        if (!empty($avatar)) {
            Db::table('store_member')->where('openid', $openid)->update(['headimg' => $avatar]);
        }
        if (!empty($nickname)) {
            Db::table('store_member')->where('openid', $openid)->update(['nickname' => $nickname, 'username' => $nickname]);
        }

        echo json_encode(array('msg' => '成功', 'code' => 200, 'data' => '请求成功'));
        exit;
    }


    //token
    public function token()
    {
        $wechat = new Wechat();
        $wx_config = $wechat->mini_config($this->header);
        $appid = $wx_config['app_id'];
        $token = Db::table("yz_access_token")->where("id=2")->find();
        if ($token) {
            $time1 = strtotime($token['time']);
            $time2 = time();
            $cha = $time2 - $time1;
            if ($cha > 3600) {
                $this->header = ['Appid' => $appid];
                $wx_config = $wechat->mini_config($this->header);
                $appid = $wx_config['app_id'];                        //小程序的appid
                $appSecret = $wx_config['app_secret'];                //小程序的$appSecret
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appSecret";

                $result = $this->http_request($url);
                $access_token = json_decode($result)->access_token;
                Db::table("yz_access_token")->where("id=2")->update(['access_token' => $access_token, 'time' => date('Y-m-d H:i:s')]);
                return $access_token;

            } else {
                return $token['access_token'];
            }
        } else {
            $this->header = ['Appid' => $appid];
            $wx_config = $wechat->mini_config($this->header);
            $appid = $wx_config['app_id'];                        //小程序的appid
            $appSecret = $wx_config['app_secret'];                //小程序的$appSecret
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appSecret";

            $result = $this->http_request($url);
            return $access_token = json_decode($result)->access_token;
        }
    }


    //获取手机号
    public function get_phone(Request $request)
    {
        $param = $request->param();
        $code = $param['code'];
        $token = $this->token();
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
        $data['code'] = $code;
        $result = $this->http_request($url, json_encode($data));
        $str = '';
        if (!empty($result)) {
            if (!empty(json_decode($result))) {
                if (!empty(json_decode($result)->phone_info)) {
                    if (!empty(json_decode($result)->phone_info->phoneNumber)) {
                        $phone = json_decode($result)->phone_info->phoneNumber;
                        if ($phone) {
                            //$id = $_POST['user_id'];
                            //Db::table("store_member")->where("id=$id")->update(["phone" => $phone]);
                            $str = json_encode(['code' => 200, 'data' => $phone, 'msg' => '请求成功']);
                        }
                    }
                }
            }
        }
        echo $str;
    }

    //Http请求
    function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }



    //获取头像
    public function getImgUrl()
    {
        header('Content-Type: application/json');

        // 1. 接收文件
        $file = $_FILES['file'] ?? null;

        if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
            echo json_encode(['code' => 400, 'msg' => '文件上传失败']);
            exit;
        }

        // 2. 验证文件类型（安全防护）
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        if (!in_array($file['type'], $allowedTypes)) {
            echo json_encode(['code' => 403, 'msg' => '仅支持jpg/png/gif格式']);
            exit;
        }

        // 3. 生成唯一文件名
        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $newFilename = uniqid('avatar_') . '.' . $extension;

        // 4. 指定存储目录（确保目录可写）
        $uploadDir =  './uploads/avatars/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        // 5. 移动临时文件
        $destination = $uploadDir . $newFilename;
        if (move_uploaded_file($file['tmp_name'], $destination)) {
            // 6. 返回永久访问地址
            $permanentUrl = sysconf('realm_name').'/uploads/avatars/' . $newFilename;
            echo json_encode([
                'code' => 200,
                'data' => ['url' => $permanentUrl]
            ]);
        } else {
            echo json_encode(['code' => 500, 'msg' => '文件保存失败']);
        }
    }


}